package com.handpay.nocardpay.baselibrary.qualificationinfo.comm;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseResponseBean;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.qualificationinfo.presenter.QualificationPresenterImpl;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.BitmapLoaderNew;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;

import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;

/**
 * Created by fplei on 2017/8/18.
 * 该类主要是辅助减少重复代码
 */

public class CommonHelper {

    public static final String KEY_FRONTPIC_URL="FRONTPIC";
    public static final String KEY_BACKPIC_URL="BACKPIC";
    public static final String KEY_HOLDPIC_URL="HOLDPIC";
    /**
     * 上传成功
     */
    public static final int UPLOAD_SUCCESS=0;
    /**
     * 上传失败
     */
    public static final int UPLOAD_FAIL=1;
    /**
     * 上传取消
     */
    public static final int UPLOAD_CANCEL=2;

    //用来区分资质图片上传还是补件上传
    public enum UploadModel{
        QUALIFICATION_UPLOADPICTURE,
        IDCARDSUPPLEMENT_UPLOADPICTURE
    }

    /**
     * 上传图片
     * @param _mActivity 上下文
     * @param qualificationPresenterImpl 上传图片操作model
     * @param uri 图片本地地址
     * @param type 上传图片类型（正面，反面，手持）
     * @param uploadModel 上传接口（资质图片/补件）
     * @return
     */
    public static boolean uploadPhotoJson(Context _mActivity,
                                    QualificationPresenterImpl qualificationPresenterImpl,
                                    String uri,
                                    BaseProtocolKey.TYPE type,
                                    UploadModel uploadModel){
        HPLog.i(HPLog.LFP_TAG,"uploadPhotoJson::uploadModel:"+uploadModel.toString());
        CRC32 mCrc32 = new CRC32();
        HashMap<String,String> params=new HashMap<String,String>();
        String acc = AccountUtils.getAccountName(_mActivity);
        String channel = ClientEngine.getInstance().CHANNEL;
        byte[] imgByte = null;
        Bitmap bitmap;
        if (uri.startsWith("http://")) {
            HPLog.i(HPLog.LFP_TAG, "uploadPhoto isHttpUrl(uri)");
            imgByte = BitmapLoaderNew.getInstance(_mActivity).loadBitmapNoCompress(uri);
        } else {
            HPLog.i(HPLog.LFP_TAG, "uploadPhoto isNotHttpUrl(uri)");
            bitmap = BitmapLoaderNew.getInstance(_mActivity).loadBitmap(_mActivity,uri, uri);
            imgByte = CommonUtils.getBitmapBytes(bitmap, BaseProtocolKey.MAXBYTE);
        }
        HPLog.i(HPLog.LFP_TAG, "  CommonUtils.getBitmapBytes after" + type + " size: " + imgByte.length / 1024);
        String imgCheck = CommonUtils.getCRC(mCrc32, imgByte);
        params.put(BaseProtocolKey.KEY_CHECK, imgCheck);
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(acc, 1, null));
        params.put(BaseProtocolKey.CHANNEL, channel);
        params.put(BaseProtocolKey.KEY_PICTYPE, String.valueOf(type.ordinal()));
        HPLog.i(HPLog.LFP_TAG,"uploadPhotoJson::params:"+params.toString());
        BaseResponseBean baseResponseBean=null;
        switch (uploadModel){
            case QUALIFICATION_UPLOADPICTURE:
                baseResponseBean= qualificationPresenterImpl.uploadQualificationPicture(params,imgByte,false);
                break;
            case IDCARDSUPPLEMENT_UPLOADPICTURE:
                baseResponseBean= qualificationPresenterImpl.uploadIDCardSupplementPicture(params,imgByte,false);
                break;
        }
        if(baseResponseBean==null){
            HPLog.i(HPLog.LFP_TAG,"baseResponseBean==null");
            return false;
        }
        HPLog.i(HPLog.LFP_TAG,"uploadPhotoJson::baseResponseBean:"+baseResponseBean.toString());
        if(baseResponseBean!=null){
            if (!TextUtils.isEmpty((baseResponseBean.errMessage)) && !TextUtils.isEmpty(baseResponseBean.responseCode)) {
                return false;
            }
        }
        return true;
    }
    //图片描述
    public static String getPicDesWithPicType(Context context,BaseProtocolKey.TYPE type){
        if(context==null)return null;
        String picDes = context.getString(R.string.ID_card_photo);
        switch (type) {
            case FRONT: {
                picDes = context.getString(R.string.ID_card_photo);
                break;
            }
            case BACK: {
                picDes = context.getString(R.string.ID_card_back_photo);
                break;
            }
            case INHAND: {
                picDes = context.getString(R.string.ID_person_with_card);
                break;
            }
        }
        return picDes;
    }
    //删除本地图片
    public static void deletePicture(String path){
        String mOutputFileUri=path;
        //这里把本地文件也删除
        if (!TextUtils.isEmpty(mOutputFileUri) && mOutputFileUri.startsWith("file:")) {
            try {
                URI fileuri = URI.create(mOutputFileUri);
                File tempfile = new File(fileuri);
                if (tempfile.exists()) {
                    tempfile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //存储照片地址到内存中
    public static void savePicUrlInMemory(String key,String value){
        ClientEngine.getInstance().saveGlobal(key,value);
    }
    //在内存中获取临时存放的地址
    public static String getPicUrlInMemory(String key){
        Object temp_obj=ClientEngine.getInstance().getGlobal(key,"");
        return CommonUtils.objectToString(temp_obj);
    }
    //清空数据
    public static void clearPicUrlInMemory(){
        ClientEngine.getInstance().saveGlobal(KEY_FRONTPIC_URL,"");
        ClientEngine.getInstance().saveGlobal(KEY_BACKPIC_URL,"");
        ClientEngine.getInstance().saveGlobal(KEY_HOLDPIC_URL,"");
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * @param URL  url地址
     * @return  url请求参数部分
     * @author lzf
     */
    public static Map<String, String> urlSplit(String URL){
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit=null;
        String strUrlParam=TruncateUrlPage(URL);
        if(strUrlParam==null){
            return mapRequest;
        }
        arrSplit=strUrlParam.split("[&]");
        for(String strSplit:arrSplit){
            String[] arrSplitEqual=null;
            arrSplitEqual= strSplit.split("[=]");
            //解析出键值
            if(arrSplitEqual.length>1){
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            }else{
                if(arrSplitEqual[0]!=""){
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    private static String TruncateUrlPage(String strURL){
        String strAllParam=null;
        String[] arrSplit=null;
        strURL=strURL.trim();
        arrSplit=strURL.split("[?]");
        if(strURL.length()>1){
            if(arrSplit.length>1){
                for (int i=1;i<arrSplit.length;i++){
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

}
